package com.longmao.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.longmao.eduservice.entity.EduCourse;
import com.longmao.eduservice.entity.EduCourseDescription;
import com.longmao.eduservice.entity.EduTeacher;
import com.longmao.eduservice.entity.vo.*;
import com.longmao.eduservice.mapper.EduCourseMapper;
import com.longmao.eduservice.service.EduChapterService;
import com.longmao.eduservice.service.EduCourseDescriptionService;
import com.longmao.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longmao.eduservice.service.EduVideoService;
import com.longmao.servicebase.constant.CourseConstant;
import com.longmao.servicebase.handler.LongMaoException;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author longmao
 * @since 2022-01-27
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService courseDescriptionService;
    
    @Autowired
    private EduVideoService videoService;
    
    @Autowired
    private EduChapterService chapterService;

    /**
     * 添加课程基本信息
     * @param courseInfoVo
     */
    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {

        //向课程表中添加课程基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int insert = baseMapper.insert(eduCourse);
        if(insert <= 0) throw new LongMaoException(20001, "添加失败");

        //获取到添加之后的课程id
        String courseId = eduCourse.getId();

        //向课程简介表中添加课程简介
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setId(courseId);
        courseDescription.setDescription(courseInfoVo.getDescription());
        courseDescriptionService.save(courseDescription);

        return courseId;
    }

    @Override
    public void pageQuery(Page<EduCourse> pageParam, CourseQuery courseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("gmt_create");

        if (courseQuery == null){
            baseMapper.selectPage(pageParam, queryWrapper);
            return;
        }

        String title = courseQuery.getTitle();
        String status = courseQuery.getStatus();

        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("title", status);
        }

        if (!StringUtils.isEmpty(status) ) {
            queryWrapper.eq("status", status);
        }

        baseMapper.selectPage(pageParam, queryWrapper);
    }

    @Override
    public CourseInfoVo getCourseInfoById(String courseId) {
        //查询课程表
        EduCourse eduCourse = baseMapper.selectById(courseId);
        if(eduCourse == null){
            throw new LongMaoException(20001, "数据不存在");
        }
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse,courseInfoVo);

        //查询简介表
        EduCourseDescription courseDescription = courseDescriptionService.getById(courseId);
        if(eduCourse != null){
            courseInfoVo.setDescription(courseDescription.getDescription());
        }
        return courseInfoVo;
    }

    @Override
    public void updateCourseInfo(CourseInfoVo courseInfo) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfo,eduCourse);

        int result = baseMapper.updateById(eduCourse);
        if(result <= 0) {
            throw new LongMaoException(20001, "课程信息保存失败");
        }

        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setDescription(courseInfo.getDescription());
        eduCourseDescription.setId(courseInfo.getId());
        boolean resultDescription = courseDescriptionService.updateById(eduCourseDescription);
        if(!resultDescription){
            throw new LongMaoException(20001, "课程详情信息保存失败");
        }
    }

    @Override
    public CoursePublishVo getPublishCourseInfo(String courseId) {
        CoursePublishVo publishCourseInfo = baseMapper.getPublishCourseInfo(courseId);
        return publishCourseInfo;
    }

    @Override
    public boolean publishCourseById(String courseId) {
        EduCourse eduCourse = new EduCourse();
        eduCourse.setId(courseId);
        eduCourse.setStatus(CourseConstant.COURSE_STATUS_Y);
        Integer result = baseMapper.updateById(eduCourse);
        return null != result && result > 0;
    }

    @Override
    public boolean deleteCourseById(String courseId) {
        //如果确定删除，则首先删除video记录，然后删除chapter记录，最后删除Course记录
        
        //根据课程 id 删除所有小节
        videoService.deleteVideoByCourseId(courseId);

        //根据课程 id 删除所有章节 chapter
        chapterService.deleteVideoByCourseId(courseId);

        //根据课程 id 删除描述
        courseDescriptionService.removeById(courseId);

        //根据 id 删除课程
        Integer result = baseMapper.deleteById(courseId);
        return null != result && result > 0;
    }

    @Cacheable(value = "course", key = "'selectCourse'")
    @Override
    public List<EduCourse> selectCourse() {
        //查询前8条热门课程
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        wrapper.last("limit 8");
        List<EduCourse> courseList = baseMapper.selectList(wrapper);
        return courseList;
    }

    @Override
    public Map<String, Object> pageCourseList(Page<EduCourse> coursePage, CourseFrontVo courseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseQuery.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQuery.getSubjectId());
        }

        if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseQuery.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }
        baseMapper.selectPage(coursePage, queryWrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("list", coursePage.getRecords());
        map.put("current", coursePage.getCurrent());
        map.put("pages", coursePage.getPages());
        map.put("size", coursePage.getSize());
        map.put("total", coursePage.getTotal());
        map.put("hasNext", coursePage.hasNext());    //是否有下一页
        map.put("hasPrevious", coursePage.hasPrevious());    //是否有上一页
        return map;
    }

    @Override
    public List<EduCourse> selectByTeacherId(String teacherId) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("teacher_id", teacherId);
        //按照最后更新时间倒序排列
        queryWrapper.orderByDesc("gmt_modified");

        List<EduCourse> courseList = baseMapper.selectList(queryWrapper);
        return courseList;
    }

    @Override
    public CourseEditVo getCourseEditInfo(String courseId) {
        return baseMapper.getCourseEditInfo(courseId);
    }
}
